<template>
  <canvas ref="canvas" @mousedown="handleMouseDown" />
</template>

<script>
import { mapState, mapMutations } from 'vuex';

export default {
  watch: {
    origin() {
      this.draw();
    },

    scale() {
      this.draw();
    },
  },

  created() {
    window.addEventListener('resize', this.handleResize);
  },

  destroyed() {
    window.removeEventListener('resize', this.handleResize);
  },

  mounted() {
    this.draw();
  },

  updated() {
    this.draw();
  },

  methods: {
    ...mapMutations(['dragStart']),

    handleResize() {
      this.draw();
    },

    handleMouseDown(ev) {
      if (ev.button === 0) {
        this.dragStart({ type: 'SELECTION', x: ev.clientX, y: ev.clientY });
      } else if (ev.button === 2) {
        this.dragStart({ type: 'ORIGIN', x: ev.clientX, y: ev.clientY });
      }
    },

    draw() {
      const gridSize = 100;
      const style = getComputedStyle(document.body);
      const lineColor = `${style.getPropertyValue('--vscode-tree-indentGuidesStroke')}33`;
      const borderColor = `${style.getPropertyValue('--vscode-charts-orange')}`;
      const ctx = this.$refs.canvas.getContext('2d');
      const width = document.body.clientWidth;
      const height = document.body.clientHeight;
      const step = gridSize * this.scale * 0.2;

      this.$refs.canvas.width = width;
      this.$refs.canvas.height = height;

      let x = (this.origin.x % gridSize) * this.scale;
      let y = (this.origin.y % gridSize) * this.scale;

      ctx.clearRect(0, 0, width, height);

      while (x > 0) {
        x -= step;
      }
      while (x < width) {
        ctx.beginPath();
        ctx.lineWidth = 1;
        ctx.strokeStyle = lineColor;
        ctx.moveTo(~~x + 0.5, 0);
        ctx.lineTo(~~x + 0.5, height);
        ctx.stroke();
        x += step;
      }

      while (y > 0) {
        y -= step;
      }
      while (y < height) {
        ctx.beginPath();
        ctx.lineWidth = 1;
        ctx.strokeStyle = lineColor;
        ctx.moveTo(0, ~~y + 0.5);
        ctx.lineTo(width, ~~y + 0.5);
        ctx.stroke();
        y += step;
      }
    },
  },

  computed: {
    ...mapState(['origin', 'scale']),
  },
};
</script>

<style scoped>
canvas {
  width: 100%;
  height: 100%;
}
</style>
